var socket=require('socket.io');
var io;
var guestNumber=1;
var nickNames={};
var namesUsed=[];
var currentRoom={};

exports.listen= function (server) {
    io=socket.listen(server);
    io.set('log level',1);
    io.sockets.on('connection', function (socket) {
        guestNumber = assignGuestName(socket,guestNumber,nickNames,namesUsed);

        joinRoom(socket,'Lobby');

        handleMessageBroadcasting(socket,nicknames);
        handleNameChangeAttempts(socket,nickNames,namesUsed);
        handleRoomJoining(socket);

        socket.on('rooms', function () {
            socket.emit('rooms',io.sockets.manager.rooms);

        });

        handleClientDisconnection(socket,nickNames,namesUsed);

    });
};

//用来处理新用户的昵称
function assignGuestName(socket,guestNumber,nickNames,namesUsed){
    var name= 'Guest_'+guestNumber;
    nickNames[socket.id]=name;
    socket.emit('nameResult',{
        success:true,
        name:name
    });

    namesUsed.push(name);
    return guestNumber+1;
}

//加入聊天室
function joinRoom(socket,room){
    socket.join(room);
    currentRoom[socket.id]=room;
    socket.emit('joinResult',{room:room});
    socket.broadcast.to(room).emit('message',{
        text:nickNames[socket.id] + ' has joined '+ room +'.'
    });

    var usersInRoom = io.sockets.clients(room);

    if(usersInRoom.length>1){
        var usersInRoomSummary='Users currently in '+room+':';
        for(var i in usersInRoom){
            var userSocketId=usersInRoom[i].id;
            if(userSocketId != socket.id){
                if(i>0){
                    usersInRoomSummary+=',';
                }
                usersInRoomSummary += nickNames[userScoketId];
            }
        }
        usersInRoomSummary += '.';

        socket.emit('message',{
            test:usersInRoomSummary
        });

    }
}

//更名
function handleNameChangeAttempts(socket,nickNames,namesUsed){
    socket.on('nameAttempt', function (name) {
        if(name.indexOf('Guest') == 0){
            socket.emit('nameResult',{
                success:false,
                message:'Names cannot begin with "Guest".'
            });
        }else{
            if(namesUsed.index(name) == -1){
                var prevName=nickNames[socket.id];
                var prevNameIdx=namesUsed.indexOf(prevName);
                namesUsed.push(name);
                nickNames[socket.id]=name;
                delete namesUsed[prevNameIdx];
                socket.emit('nameResult',{
                    success:true,
                    name:name
                });
                socket.broadcast.to(currentRoom[socket.id]).emit('message',{
                    text:prevName + 'is now know as '+ name +'.'
                });
            }else{
                socket.emit('nameResult',{
                    success:false,
                    message:'That name is already in use.'
                });
            }
        }
    });
}

//发送聊天消息
function handleMessageBroadcasting(socket){
    socket.on('message', function (message) {
        socket.broadcast.to(mssage.room).emit('message',{
            text:nickNames[socket.id] + ':' + message.text
        });
    });
}

//创建房间
function handleRoomJoining(socket){
    socket.on('join', function (room) {
        socket.leave(currentRoom[socket.id]);
        joinRoom(socket,room.newRoom);
    });
}

//用户断开链接
function handleClientDisconnection(socket){
    socket.on('disconnect', function () {
        var nameIdx=namesUsed.indexOf(nickNames[socket.id]);
        delete namesUsed[nameIdx];
        delete nickNames[socket.id];
    });
}


